package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.generateRFC;

import java.sql.ResultSet;
import java.util.ArrayList;

import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.RFCMaker;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.database.DatabaseConnection;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.model.RFC;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.generateRFCPanel.GenerateRFCPanel;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.generateRFCPanel.generateRFCSubs.ChooseEditRFCDialog;

public class LoadOwnRFCinDialogListThread extends Thread {

	private ChooseEditRFCDialog chooseEditRFCDialog;
	private GenerateRFCPanel generateRFCPanel;
	private DatabaseConnection connection;
	
	public LoadOwnRFCinDialogListThread(GenerateRFCPanel generateRFCPanel, ChooseEditRFCDialog chooseEditRFCDialog){

		this.generateRFCPanel = generateRFCPanel;
		this.chooseEditRFCDialog = chooseEditRFCDialog;
	}
	
	public void run()
	{
		loadUnfinishedRFC();
	}

	private void loadUnfinishedRFC()
	{
		connection = new DatabaseConnection();
		connection.connect();
		
		String name = generateRFCPanel.getMainframe().getSignedInUser()
				.getFirstname()
				+ " "
				+ generateRFCPanel.getMainframe().getSignedInUser().getName();
		
		String query = "SELECT * FROM CMS_RFC WHERE "+ RFC.TC_RFCINITIATOR + " = '" +name+"' AND "+ RFC.TC_Status+" = 'unfinished'";
		
		ResultSet rs = connection.query(query);
		int count = 0;
		ArrayList<RFC> rfcs = new ArrayList<RFC>();
				
		try
		{
			while (rs.next())
			{
				count++;
				RFCMaker maker = new RFCMaker();		
				rfcs.add(maker.makeanRFC(rs));
			}
		}
		catch(Exception e)
		{}
		
		if(count == 0)
		{
			this.chooseEditRFCDialog.getDisplayTable().displayNoElenemt();
		}
		
		this.chooseEditRFCDialog.getDisplayTable().setVisible(false);
		for(RFC rfc : rfcs)
		{
			this.chooseEditRFCDialog.getDisplayTable().addRFCinTable(rfc);
		}
		this.chooseEditRFCDialog.getDisplayTable().setVisible(true);
		
		connection.disconnect();
		this.chooseEditRFCDialog.getProgress().setVisible(false);
	}
}